﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LitTools
{
    /// <summary>
    /// 存档模块
    /// </summary>
    public class StorageModule
    {
        // 脏标记
        private bool isDirty = false;
        //当前存档行为
        private SaveStrategy curSaveStrategy;
        //上次保存时间
        private float lastWriteTime = -1;
        //默认存档间隔为0.5秒
        private float saveInterval = 0.5f;

        public const string EncryptKey = "abcdefghijklmnop";
        public const string EncryptIV = "12345678";

        /// <summary>
        /// 构造方法
        /// </summary>
        public StorageModule(SaveStrategy stragegy, float saveInterval = .5f)
        {
            curSaveStrategy = stragegy;
            curSaveStrategy.Init();
            if (saveInterval >= .05f)
            {
                this.saveInterval = saveInterval;
            }
            else
            {
                Debug.LogError("保存间隔不能低于0.05s");
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        public void SaveData<T>(T data, bool saveImmediately = false) where T : SaveData<T>, new()
        {
            curSaveStrategy.SaveData(data);
            isDirty = true;
            if (saveImmediately)
                WriteToDisk();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T LoadData<T>() where T : SaveData<T>, new()
        {
            return curSaveStrategy.LoadData<T>();
        }

        /// <summary>
        /// 写入磁盘
        /// </summary>
        public void WriteToDisk()
        {
            curSaveStrategy.WriteToDisk();
            isDirty = false;
        }


        /// <summary>
        /// 模块更新
        /// </summary>
        public void Update()
        {
            if (!isDirty) return;
            if (Time.realtimeSinceStartup - lastWriteTime < saveInterval) return;

            //默认一秒最大保存一次
            WriteToDisk();
            lastWriteTime = Time.realtimeSinceStartup;
            Debug.Log("SaveManager Auto Save");
        }
    }
}